package com.example.config.securityAllconfig;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.domain.User;
import com.example.service.IUserService;
import com.example.util.JwtUtil;
import com.example.util.Result;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class MyLogoutSuccesshandle implements LogoutSuccessHandler {

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private IUserService userService;
    @Override
    public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {

        String jwtToken = httpServletRequest.getHeader("Authorization");
        if (StringUtils.isEmpty(jwtToken)){
            Result result=Result.builder()
                    .flag(false)
                    .msg("header为空")
                    .build();
            printToken(httpServletRequest, httpServletResponse,result);
            return;
        }

        boolean verifyToken = jwtUtil.verifyToken(jwtToken);
        if (!verifyToken){
            Result result=Result.builder()
                    .flag(false)
                    .msg("jwt非法")
                    .build();
            printToken(httpServletRequest, httpServletResponse,result);
            return;
        }
        String s = stringRedisTemplate.opsForValue().get("logintoken" + jwtToken);
        System.out.println(s);
        JsonNode jsonNode = objectMapper.readTree(s);

        // 获取name字段的值
        String username = jsonNode.get("name").asText();
        User login = userService.getOne(new QueryWrapper<User>().eq("phone", username));
        //判断用户状态
        if(!login.getStatus().equals(2)){
            Result r1 = Result.builder()
                    .flag(true)
                    .msg("操作失败，当前用户未登录或已封号")
                    .data(login.getUsername())
                    .build();
            printToken(httpServletRequest, httpServletResponse,r1);
        }
        login.setStatus(1);
        userService.updateById(login);
        Result r1 = Result.builder()
                .flag(true)
                .msg("登出成功")
                .data(login.getUsername())
                .build();
        printToken(httpServletRequest, httpServletResponse,r1);
        stringRedisTemplate.delete("logintoken"+jwtToken);


    }
    public void printToken(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,Result build) throws IOException {
        String s = objectMapper.writeValueAsString(build);
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json,charset=UTF-8");
        PrintWriter writer = httpServletResponse.getWriter();
        writer.print(s);
        writer.flush();

    }
}
